package br.mg.bhe.ftpobre.command;

import java.io.File;

import br.mg.bhe.ftpobre.fs.LocalFile;
import br.mg.bhe.ftpobre.log.FtpLogView;
import br.mg.bhe.ftpobre.util.LocalFileUtil;

/**
 * 
 * @author Aureliano
 */
public class DeleteLocalFileCommand implements ICommand {

	private StringBuilder message;
	
	@Override
	public void execute() {
		if (this.canExecute()) {
			this.doAction();
		}
	}

	@Override
	public boolean canExecute() {
		LocalFile file = LocalFileUtil.getSelectedFile();		
		return ((file != null) && (!LocalFile.getUpFolder().equals(file)));
	}

	private void doAction() {
		LocalFile file = LocalFileUtil.getSelectedFile();
		this.message = new StringBuilder("Excluindo objeto '" + file.getPath() + "'");
		this.delete(new File(file.getPath()));
		FtpLogView.log(this.message.toString());
		CommandFactory.command(RefreshLocalFilesViewCommand.class).execute();	
	}
	
	private void delete(File file) {
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			
			for (File f : files) {
				this.delete(f);
			}
		}

		file.delete();
		this.message.append("\n\tObjeto '" + file.getPath() + "' excluído.");
	}
}